﻿@using Seal.Model;
@{
    ReportTask task = Model;

    task.TemplateDescription = "Load a report Model result table into the current database. The 'Execution Step' must be set after the models generations. If the model is not referenced in a View, set the main view option 'Load all models' to true.";
    task.Step = ExecutionStep.BeforeRendering;

    //Parameters for this task
    task.Parameters.Add(new Parameter() { Name = "model_name", Value = "", DisplayName = "Model name", Description = "The model name. If empty, all the models of the report will be loaded to the database.", Enums = new string[] { "MetaColumn" }, UseOnlyEnumValues = false });
    task.Parameters.Add(new Parameter() { Name = "table_name_prefix", Value = "", DisplayName = "Optional prefix for the destination table name", Description = "A prefix for the destination table created in the database." });
    task.Parameters.Add(new Parameter() { Name = "table_name", Value = "", DisplayName = "Destination table name", Description = "The name of the destination table created in the database. If empty, the name of the model is used." + ReportTask.TranslatedParameterDescription });
    task.Parameters.Add(new Parameter() { Name = "show_hidden_elements", BoolValue = false, DisplayName = "Create hidden elements", Description = "If true, columns for hidden elements are created in the table (e.g. identifiers for sub-report or drill navigation)." });

    task.Script = @"@using System.Data
@{
    ReportTask task = Model;
    var helper = new TaskHelper(task);

    var modelName = task.GetValue(""model_name"");
    var tableNamePrefix = task.GetValue(""table_name_prefix"");
    var tableName = task.GetValueTranslated(""table_name"");
    var showHidden = task.GetBoolValue(""show_hidden_elements"", false);

    foreach (var model in task.Report.Models)
    {
        if (string.IsNullOrEmpty(modelName) || model.Name == modelName) {
            //Get the model result table
            var dt = model.ResultTable;
            if (dt != null) {
                var cnt = 0;
                foreach (var el in model.Elements) {
                    if (!showHidden && (el.IsForNavigation || el.PivotPosition == PivotPosition.Hidden)) {
                        //Element is hidden
                        dt.Columns.Remove(el.SQLColumnName);
                    }
                    else {
                        var col = dt.Columns[el.SQLColumnName];
                        if (col != null) {
                            col.ColumnName = el.DisplayNameElTranslated;
                            col.SetOrdinal(cnt++);
                        }
                    }
                }    
                //Save to the database
                dt.TableName = tableNamePrefix+ (string.IsNullOrEmpty(tableName) ? model.Name : tableName);
                helper.LoadTable(dt);
            }
        }
    }
}
";

    task.BodyScript = ReportTask.BodyScriptTemplate;
}
